<?php
/**
 * Created by PhpStorm.
 * User: 陶然
 * Date: 2019/4/9
 * Time: 18:34
 * SOURCE: 中国大陆工时规管现况（标准工时）：
 *              一天工作时间为8小时，平均每周工时不超过40小时;
 *              加班上限为一天3小时及一个月36小时，逾时工作薪金不低于平日工资的150％。
 *              而一周最高工时则为48小时。平均每月计薪天数为21.75天。
 * TO: 我是陶然,健康撸代码,拒绝通宵。
 * CLASS: < 账户管理 >
 */

namespace App\HttpController\Taoran;

use App\Common\Checking;
use App\Common\Sms;
use App\HttpController\V1\Auth;
use think\image\Exception;

class Accounts extends Auth
{
    /**
     * @return bool
     * 账户管理页面
     */
    function accounts(){
        $last=$this->db->where('user_id',$this->user->id)->where('status','on')->get('payment',null,'type');
        $list=['bank'=>0,'wechat'=>0,'alipay'=>0,'repass'=>0,'cash_start'=>0,'cash_charge'=>0,'balance'=>0];
        foreach ($last as $v){
            $list[$v['type']]=1;
        }
        if ($this->db->where('id',$this->user->id)->getValue('users','pay_password')){
            $list['repass']=1;
        }
        $cash_start=$this->db->where('name','cash_start')->getValue('config','value');
        $cash_charge=$this->db->where('name','cash_charge')->getValue('config','value');
        $balance=$this->db->where('id',$this->user->id)->getValue('users','balance');
        $phone=$this->db->where('id',$this->user->id)->getValue('users','mobile');
        $wx_openid=$this->db->where('id',$this->user->id)->getValue('users','wx_openid');
        if($cash_start){
            $list['cash_start']=$cash_start;
        }
        if($cash_charge){
            $list['cash_charge']=$cash_charge;
        }
        if($balance){
            $list['balance']=$balance;
        }
        $list['phone']=$phone;
        $list['wx_log']=0;
        if ($wx_openid!='' &&$wx_openid!=null){
            $list['wx_log']=1;
        }
        return $this->writeJson(200,$list,'');
    }

    /**
     * @return bool
     * 绑定银行卡
     */
    function band_bank()
    {
        $parmer=$this->input('','post');
        if($this->kuhn($parmer['card'])!==true){
            return $this->writeJson(201,'','请输入正确的银行卡');
        }
        if (!preg_match("/[\x7f-\xff]/", $parmer['name'])){
            return $this->writeJson(202,'','请输入正确的银行名称');
        }
        if (!preg_match("/[\x7f-\xff]/", $parmer['branch'])){
            return $this->writeJson(203,'','请输入正确的支行名称');
        }
        if (!preg_match("/[\x7f-\xff]/", $parmer['truename'])){
            return $this->writeJson(204,'','请输入正确的真实姓名');
        }
        if (strlen($parmer['code'])!=6){
            return $this->writeJson(205,'','请输入六位验证码');
        }
        $mobile=$this->db->where('id',$this->user->id)->getValue('users','mobile');
        $sms=new Sms();
        $this->db->startTransaction();
        try {
            $msg=$sms->confirmation($mobile, $parmer['code'], 5, $this->db);
            if ($msg['status']!=1) {
                throw new \Exception($msg['msg'],$msg['status']);
            }
            unset($parmer['code']);
            $data = [
                'user_id' => $this->user->id,
                'varchar' => json_encode($parmer),
                'type' => 'bank',
                'createtime' => date('YmdHis')
            ];
            $sql = $this->db->insert('payment', $data);
            if (!$sql) {
                throw new \Exception('绑定失败,请稍后重试',207);
            }
            $this->db->commit();
            return $this->writeJson(200,'','绑定成功');
        }catch (\Exception $e){
            $this->db->rollback();
            return $this->writeJson($e->getCode(), '', $e->getMessage());
        }
    }

    /**
     * @return bool
     * 解绑银行卡页面
     */
    function untying_bank_page()
    {
        $bankData=$this->db->where('user_id',$this->user->id)->where('type','bank')->where('status','on')->getOne('payment');
        if (!$bankData){
            return $this->writeJson(201,'','暂未绑定银行卡');
        }
        $data=json_decode($bankData['varchar'],true);
        $mobile=$this->db->where('id',$this->user->id)->getValue('users','mobile');
        if (!$mobile){
            return $this->writeJson(201,'','暂未绑定手机号');
        }
        $data['mobile']=substr($mobile, 0, 3).'****'.substr($mobile, 7);
        return $this->writeJson(200,$data);
    }

    /**
     * @return bool
     * 银行卡解绑
     */
    function untying_bank()
    {
        $code=$this->input('code','post');
        if (strlen($code)!=6){
            return $this->writeJson(201,'','请输入六位验证码');
        }
        $sms=new Sms();
        $mobile=$this->db->where('id',$this->user->id)->getValue('users','mobile');
        $this->db->startTransaction();
        try{
            $msg=$sms->confirmation($mobile,$code,7,$this->db);
            if ($msg['status']!=1){
                throw new \Exception($msg['msg'],$msg['status']);
            }
            $sql=$this->db->where('user_id',$this->user->id)->where('type','bank')->where('status','on')->update('payment',['status'=>'off']);
            if (!$sql){
                throw new \Exception('银行卡解绑失败',202);
            }
            $this->db->commit();
            return $this->writeJson(200,'','银行卡解绑成功');
        }catch (\Exception $e){
            $this->db->rollback();
            return $this->writeJson($e->getCode(), '', $e->getMessage());
        }
    }

    /**
     * @return bool
     * 修改密码
     * type  1登录密码   2支付密码 3设置登陆密码
     */
    function editPass()
    {
        $param=$this->input('','post');
        try {
            if (!Checking::keyIsExistence('type,code,pass,repass', $param)) {
                throw new \Exception(Checking::MESSAGE['keyIsExistence'], 201);
            }
            if (!in_array($param['type'], [1, 2,3])) {
                throw new \Exception('没有这个操作', 202);
            }
            if ($param['pass'] != $param['repass']) {
                throw new \Exception('两次密码输入不一致', 203);
            }
            $passRule=$param['type']==1?(Checking::passwordRule($param['pass'])):(Checking::transactionPwdRule($param['pass']));
            if (!$passRule) {
                throw new \Exception(Checking::MESSAGE['passwordRule'],204);
            }
            $sms=new Sms();
            $mobile=$this->db->where('id',$this->user->id)->getValue('users','mobile');
            $this->db->startTransaction();
            $msg=$sms->confirmation($mobile,$param['code'],$param['type']==1?8:($param['type']==2?9:3),$this->db);
            if($msg['status']!=1){
                throw new \Exception($msg['msg'],$msg['status']);
            }
            $data[$param['type']==1?'password':'pay_password']=Checking::passwordHash($param['pass']);
            $data['updatetime']=date('YmdHis');
            $sql=$this->db->where('id',$this->user->id)->update('users',$data);
            if (!$sql){
                throw new Exception($param['type']==3?'设置失败':'修改失败',205);
            }
            $this->db->commit();
            return $this->writeJson(200,'',$param['type']==3?'设置成功':'修改成功');
        }catch (\Exception $e){
            $this->db->rollback();
            return $this->writeJson($e->getCode(),'',$e->getMessage());
        }
    }

    /**
     * @param $number
     * @return bool
     * kuhn判断银行卡号是否存在
     */
    function kuhn($number)
    {
        $arr_no = str_split($number);
        $last_n = $arr_no[count($arr_no)-1];
        krsort($arr_no);
        $i = 1;
        $total = 0;
        foreach ($arr_no as $n){
            if($i%2==0){
                $ix = $n*2;
                if($ix>=10){
                    $nx = 1 + ($ix % 10);
                    $total += $nx;
                }else{
                    $total += $ix;
                }
            }else{
                $total += $n;
            }
            $i++;
        }
        $total -= $last_n;
        $total *= 9;
        if($last_n == ($total%10)){
            return true;
        }
        return false;
    }

    /**
     * @return bool
     * 支付宝微信绑定页面渲染
     * 1 支付宝  2微信
     */
    function alipay()
    {
        $type='wechat';
        if ($this->input('type','post')==1){
            $type='alipay';
        }
        $alipay=$this->db->where('user_id',$this->user->id)->where('type',$type)->where('status','on')->getOne('payment');
        if (!$alipay){
            return $this->writeJson(201,'','尚未绑定');
        }
        return $this->writeJson(200,QINIU_URL.$alipay['varchar'],'成功');
    }

    /**
     * @return bool
     * 支付宝微信绑定
     * 1 支付宝  2微信
     */
    function binding()
    {
        $image=$this->input('images','post');
        if (!strstr($image,QINIU_URL)){
            return $this->writeJson(201,'请上传正确的图片地址');
        }
        $images=str_replace(QINIU_URL,null,$image);
        $type='wechat';
        if ($this->input('type','post')==1){
            $type='alipay';
        }
        try{
            $this->db->startTransaction();
            $data = [
                'user_id' => $this->user->id,
                'varchar' => $images,
                'type' => $type,
                'createtime' => date('YmdHis')
            ];
            $sql=$this->db->where('user_id',$this->user->id)->where('type',$type)->where('status','on')->update('payment',['status'=>'off']);
            if (!$sql) {
                throw new \Exception('解绑失败,请稍后再试',203);
            }
            $sql = $this->db->insert('payment', $data);
            if (!$sql){
                throw new \Exception('绑定失败,请稍后重试',202);
            }
            $this->db->commit();
            return $this->writeJson(200,'绑定成功');
        }catch (\Exception $e){
            $this->db->rollback();
            return $this->writeJson($e->getCode(),$e->getMessage());
        }
    }
}
